<?php
//分页
function gourl_pagenav($count=0, $limit=20, $paged=1, $url='') {
	$maxpage = ceil($count / $limit);
	if($maxpage <= 1 || !$url) return;
	$baseurl = admin_url($url);
	$baseurl .= strpos($baseurl, '?') !== false ? '&amp;pn=' : '?pn=';
	if(!$paged) $paged = 1;

	$out = '<div class="tablenav-pages"><span class="displaying-num">共' . $count . '个项目</span><span class="pagination-links">';
	if($paged <= 2) {
		$out .= ' <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&laquo;</span>';
	} else {
		$out .= ' <a class="first-page button" href="' . $baseurl . '1"><span aria-hidden="true">&laquo;</span></a>';
	}
	if($paged == 1) {
		$out .= ' <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&lt;</span>';
	} else {
		$out .= ' <a class="prev-page button" href="' . $baseurl . ($paged-1) . '"><span aria-hidden="true">&lt;</span></a>';
	}
	$out .= ' <span class="tablenav-paging-text">第' . $paged . '页，共' . $maxpage . '页</span>';
	if($paged >= $maxpage) {
		$out .= ' <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&gt;</span>';
	} else {
		$out .= ' <a class="next-page button" href="' . $baseurl . ($paged+1) . '"><span aria-hidden="true">&gt;</span></a>';
	}
	if($paged+1 >= $maxpage) {
		$out .= ' <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&raquo;</span>';
	} else {
		$out .= ' <a class="last-page button" href="' . $baseurl . $maxpage . '"><span aria-hidden="true">&raquo;</span></a>';
	}
	$out .= '</span></div>';
	return $out;
}
//生成短代码
function gourl_generate_code($code='') {
	global $wpdb;
	$code = $code ? $code : wp_generate_password(8, false);
	while($wpdb->get_var($wpdb->prepare("SELECT ID FROM gourls WHERE code=%s LIMIT 1", $code))) {	
		$code = wp_generate_password(8, false);
	}
	return $code;
}
//URL重写
function gourl_rewrite_rules($wp_rewrite) {
	$new_rules = array(
		'go/([^/]+)$' => 'index.php?pagename=go&code=$matches[1]'
	);
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'gourl_rewrite_rules', 10, 1);

//添加页面查询参数
function gourl_add_query_vars($query_vars) {
	$query_vars[] = 'code';
	return $query_vars;
}
add_action('query_vars', 'gourl_add_query_vars', 10, 1);

//页面跳转
function gourl_redirect($query) {
	global $wpdb;
	if(!isset($query->query_vars['pagename']) || $query->query_vars['pagename'] != 'go') {
		return;
	}
	$code = $query->query_vars['code'];
	$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM gourls WHERE code=%s LIMIT 1", $code));
	$url = is_object($row) ? $row->url : home_url();
	wp_redirect($url, 302);
    exit;
}
add_action('parse_request', 'gourl_redirect', 10 , 1);

//Robots
function gourl_robots($output) {
	$output .= 'Disallow: /go/';
	return $output;
}
add_filter('robots_txt', 'gourl_robots', 10, 1);

//过滤链接rel属性
function gourl_targeted_link_rel($rel, $link_html) {
	$gourl = preg_quote(home_url('/') . 'go/', '/');
	if(!preg_match("/href=['\"]{$gourl}.*['\"]/i", $link_html)) return $rel;

	return 'noopener nofollow';
}
add_filter('wp_targeted_link_rel', 'gourl_targeted_link_rel', 10, 2);

//过滤内容中的网址
function gourl_the_content($content) {
	global $wpdb;
	if(!is_singular() || !is_main_query()) return $content;

	preg_match_all('/<a.*href=[\'|\"](https?:\/\/.*)[\'|\"].*>(?:<.*(?:alt|title)=[\'|\"])?([^<>]*)(?:[\'|\"].*)?<\/a>/iU', $content, $matchs);
	if(!$matchs) return $content;

	$domain = parse_url(get_option('siteurl'), PHP_URL_HOST);
	$gourl = home_url('/') . 'go/';

	$old = $matchs[0];
	$new = array();
	foreach($matchs[1] as $key=>$link) {
		$url = wp_specialchars_decode(rtrim($link, '/'));
		$url = esc_url_raw($url);
		$domain2 = parse_url($link, PHP_URL_HOST);
		if($domain2 == $domain) {
			unset($old[$key]);
			continue;
		}

		$cache_key = md5($url);
		$code = wp_cache_get($cache_key, 'gourl');
		if(!$code) {
			$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM gourls WHERE url=%s LIMIT 1", $url));
			if(is_object($row)) {
				$code = $row->code;
			} else {
				//生成短代码并写入数据库
				$note = $matchs[2][$key];
				if(filter_var($note, FILTER_VALIDATE_URL) !== false) {
					$note = '';
				}
				$code = gourl_generate_code();
				$wpdb->insert('gourls', array(
					'code' => $code,
					'url' => $url,
					'note' => $note
				), array('%s', '%s', '%s'));
			}

			wp_cache_add($cache_key, $code, 'gourl');
		}

		//替换链接
		$link = preg_quote($link, '/');
		$new[$key] = preg_replace("/{$link}/",  $gourl . $code, $matchs[0][$key], 1);
		$new[$key] = wp_targeted_link_rel($new[$key]);
	}

	//如果存在外部链接则进行替换
	if($new) {
		$content = str_replace($old, $new, $content);
	}
	return $content;
}
add_filter('the_content', 'gourl_the_content', 10, 1);
?>
